import { asyncRoutes, constantRoutes } from '@/router'
import {findMenus} from '@/api/user'
import Layout from "@/layout";
/**
 * Use meta.role to determine if the current user has system
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}



/**
 * 静态路由懒加载
 * @param view  格式必须为 xxx/xxx 开头不要加斜杠
 * @returns
 */
export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}.vue`], resolve)
}
/**
 * 把从后端查询的菜单数据拼装成路由格式的数据
 * @param routes
 * @param data 后端返回的菜单数据
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];
  routes.forEach((route) => {
    const tmp = {...route };
    if (hasPermission(roles, tmp)) {
      // if(tmp.component === '#'){
      //   tmp.component=Layout;
      // }else
      // if(tmp.component === '#1'){
      //   tmp.component=Layout2;
      // }else {
      //   tmp.component=loadView(tmp.component);
      // }
      tmp.component=tmp.component === '#' ? Layout : loadView(tmp.component);
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });
  return res;
}



const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}



const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      findMenus().then(response=>{
        const menuData = Object.assign([], response.data)
        const accessedRoutes = filterAsyncRoutes(menuData,roles)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      });


    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
